<?php
namespace work {

    use app\ctr;
    use C\mod\siginIn;
    use C\mod\worker;
    use C\mod\workerType;
    use C\mod\location;
    use C\mod\pieceState;
    use C\mod\areaWorker;
    use C\mod\area;
    use C\mod\orderPiece;
    use C\mod\city;
    use C\mod\site;
    use C\mod\express;
    class user extends ctr {

        // --- 判断登录 ---
        public function isLogined() {
            
            if($post = $this->getAesPost()) {
                if (isset($_SESSION['worker.id'])) {
                    if ($worker = worker::get(['id' => $_SESSION['worker.id']])) {
                        $types = [];
                        $workerTypes = workerType::getList(['worker_id' => $worker->id]);
                        foreach ($workerTypes as $workerType)
                            $types[] = $workerType->type;
                        $sites = site::getList(['available' => 1]);
                        $jSites = [];
                        foreach($sites as $site) {
                            $jSites[] = [
                                'id' => $site->id,
                                'name' => $site->name
                            ];
                        }
                        $citys = city::getList(['available' => 1, 'is_city' => 1]);
                        $cityIds = [];
                        foreach($citys as $city) {
                            $cityIds[] = [
                                'id' => $city->id,
                                'name' => $city->name
                            ];
                        }
                        $jexpresss = [];
                        $expresss = express::getList(['available' => 1]);
                        foreach($expresss as $express) {
                            $jexpresss[] = [
                                'id' => $express->id,
                                'name' => $express->name
                            ];
                        }
                        $this->writeAesJson(1, [
                            'types' => $types,
                            'pwdState' => $worker->pwd_state,
                            'cityIds' => $cityIds,
                            'sites' => $jSites,
                            'expresss' => $jexpresss
                        ], 1);
                    } else
                        $this->writeAesJson(1, 1);
                } else
                    $this->writeAesJson(1, 1);
            }
        }

        // --- 登录 ---
        public function login() {

            if($post = $this->getAesPost()) {
                if($worker = worker::get(['user' => trim($post['user'])])) {
                    $pwd = md5(md5($post['pwd']) . $worker->salt);
                    if($worker->pwd == $pwd) {
                        if(isset($post['device'])) {
                            $worker->set([
                                'device' => $post['device']
                            ]);
                            $worker->update();
                        }
                        $types = [];
                        $workerTypes = workerType::getList(['worker_id' => $worker->id]);
                        foreach($workerTypes as $workerType) {
                            $types[] = $workerType->type;
                        }
                        $citys = city::getList(['available' => 1, 'is_city' => 1]);
                        $cityIds = [];
                        foreach($citys as $city) {
                            $cityIds[] = [
                                'id' => $city->id,
                                'name' => $city->name
                            ];
                        }
                        $sites = site::getList(['available' => 1]);
                        $jSites = [];
                        foreach($sites as $site) {
                            $jSites[] = [
                                'id' => $site->id,
                                'name' => $site->name
                            ];
                        }
                        $_SESSION['worker.id'] = $worker->id;

                        $jexpresss = [];
                        $expresss = express::getList(['available' => 1]);
                        foreach($expresss as $express) {
                            $jexpresss[] = [
                                'id' => $express->id,
                                'name' => $express->name
                            ];
                        }

                        $this->writeAesJson(1,[
                            'types' => $types,
                            'pwdState' => $worker->pwd_state,
                            'sites' => $jSites,
                            'cityIds' => $cityIds,
                             'expresss' => $jexpresss
                        ],1);
                    } else
                        $this->writeAesJson(0, '密码错误，请您核对密码', 1);
                } else
                    $this->writeAesJson(0, '用户名不存在', 1);
            }
        }


        // --- 修改密码 ---
        public function updatePwd() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $salt = rand(1000, 9999);
                $pwd = trim($post['pwd']);
                if (preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,16}$/', $pwd)) {
                    $worker->set([
                        'pwd' => md5(md5($pwd) . $salt),
                        'salt' => $salt,
                        'pwd_state' => 1
                    ]);
                    $worker->update();
                    $this->writeAesJson(1, 1);
                } else
                    $this->writeAesJson(0, '请输入6-16位，必须包含字母和数字', 1);
            }
        }

        // --- 定时定位 ---
        public function location() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $lat = trim($post['lat']+0);
                $lng = trim($post['lng']+0);
                $acc = trim($post['acc']+0);
                $dir = trim($post['dir']+0);
                $locations = location::getList(['worker_id' => $worker->id],[0, 1], ['id', 'DESC']);
                $times = [];
                foreach($locations as $location) {
                    $times[] = $location->time_add;
                }

                if(count($times)) {
                    $timeInt = intval($times[0]);
                } else {
                    $timeInt = 0;
                }
                $time = $_SERVER['REQUEST_TIME'] - $timeInt;
                //--- 判断操作是否小于半分钟 ---
                if($time > 30) {
                    $locationAdd = new location();
                    $locationAdd->set([
                        'worker_id' =>$worker->id,
                        'lat' => $lat,
                        'lng' => $lng,
                        'time_add' => $_SERVER['REQUEST_TIME']
                    ]);
                    $locationAdd->create();
                }
                $worker->set([
                    'lat' => $lat,
                    'lng' => $lng,
                    'acc' => $acc,
                    'dir' => $dir,
                    'time_update' => $_SERVER['REQUEST_TIME']
                ]);
                $worker->update();
                $this->writeAesJson(1, 1);
            }
        }


        // --- 获取其他人定位 ---
        public function getLocation() {

            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($post['lat']) && isset($post['lng']) && $post['lng'] != '' && $post['lat'] != '') {
                    $workerId = $worker->id;
                    $locations = [];
                    $workerIds = [];
                    $getLocations = worker::scope($post['lat'], $post['lng'], $workerId);

                    foreach ($getLocations as $getLocation) {
                        $locations[] = [
                            'id' => $getLocation->id,
                            'lat' => $getLocation->lat,
                            'lng' => $getLocation->lng,
                            'realname' =>$getLocation->realname,
                            'phone' => $getLocation->phone
                        ];
                        $workerIds[] = $getLocation->id;
                    }

                    $workerTypes = [];
                    if (count($workerIds)>0) {    // by  xuic
                        $type = [0,1,2,3];
                        $workerTs = workerType::getList(['defaults' => 1, ['worker_id', 'in', $workerIds],['type','in',$type]]);
                        foreach ($workerTs as $workerT) {
                            $workerTypes[] = ['id' => $workerT->worker_id, 'type' => $workerT->type];
                        }
                    }

                    $this->writeAesJson(1, [
                        'locations' => $locations,
                        'workertypes' => $workerTypes
                    ], 1);
                } else
                    $this->writeAesJson(0, '缺少经纬度', 1);
            }
        }

        // --- 当前工作人员的个人信息 ---
        public function getInfo() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $types = [];
                $workerTypes = workerType::getList(['worker_id' => $worker->id]);
                foreach ($workerTypes as $workerType) {
                    $types[] = $workerType->type;
                }
                $this->writeAesJson(1, [
                    'user' => $worker->user,
                    'realname' => $worker->realname,
                    'phone' => $worker->phone,
                    'types' => $types
                ], 1);
            }
        }

        // --- 当前工作人员的历史订单 ---
        public function historyOrder() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($_POST['lastId']) && trim($_POST['lastId']) != '') {
                    $lastId = trim($_POST['lastId'] + 0);
                } else {
                    $lastId = 0;
                }
                if($post['lastId'] == 0) {
                    $lastId = ['id','>',$lastId];
                } else {
                    $lastId = ['id','<',$lastId];
                }
                $orders = [];
                $orderIds = [];
                $orderPieces = [];
                $stateIn = [];
                if($post['state'] == 'sender') {
                    $stateIn[] = [1,2,3,4,5,6];
                } else {
                    $stateIn[] = [7,8,9,10,11];
                }

                $workerOrders = pieceState::getList(['worker_id' => $worker->id,  $lastId, ['state_in','in',$stateIn[0]]], [0, 10], ['id', 'DESC']);

                foreach ($workerOrders as $workerOrder) {
                    $orders[] = [
                        'id' => $workerOrder->id,
                        'pieceId' => $workerOrder->piece_id,
                        'stateIn' => $workerOrder->state_in,
                        'timeAdd' => $workerOrder->time_add
                    ];
                    $orderIds[] = $workerOrder->piece_id;
                }
                if(count($orderIds) > 0) {
                    $orderPs = orderPiece::getList([['id', 'in', $orderIds]]);
                    foreach ($orderPs as $orderP) {
                        $orderPieces[] = [
                            'pieceId' => $orderP->id,
                            'pieceCode' => $orderP->piece_code,
                            'name' => $orderP->name_recipient,
                            'phone' => $orderP->phone_recipient,
                            'address' => $orderP->address_recipient,
                            'time' => date('m月d日 H:i:s', $orderP->time_add)
                        ];
                    }
                }
                $this->writeAesJson(1, [
                    'historyOrders' => $orders,
                    'pieceCodes' => $orderPieces
                ], 1);
            }
        }

        // --- 当前用户签到 ---
        public function siginIn() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $sigin = siginIn::getList(['worker_id' => $worker->id],[0, 1], ['id', 'DESC']);

                $time = isset($sigin[0]) ? $sigin[0]->time_add : false;

                if ( !$time || date('Y-m-d') != date('Y-m-d',$time)) {
                    $areaIds = [];
                    $lat = trim($post['lat'] + 0);
                    $lng = trim($post['lng'] + 0);
                    if ($areas = area::scope($lat, $lng)) {
                        foreach ($areas as $area) {
                            $areaIds[] = $area->id;
                        }
                        if (areaWorker::getList([['area_id', 'in', $areaIds],'worker_id' => $worker->id])) {
                            $sigin = new siginIn();
                            $sigin->set([
                                'worker_id' => $worker->id,
                                'time_add' => $_SERVER['REQUEST_TIME'],
                                'lat' => $lat,
                                'lng' => $lng
                            ]);
                            $sigin->create();
                            $this->writeAesJson(1, 1);
                        } else
                            $this->writeAesJson(0, '还未进工作区域', 1);
                    } else
                        $this->writeAesJson(0, '签到失败', 1);
                } else
                    $this->writeAesJson(0, '今天已签到', 1);
            }
        }

        // --- 退出登录 ---

        public function logout() {

            if(($this->getAesPost()) && ($worker = $this->getLogWorker())) {
                unset($_SESSION['worker.id']);
                if(isset($post['device'])) {
                    $worker->set([
                        'device' => ''
                    ]);
                    $worker->update();
                }
                $this->writeAesJson(1, 1);
            }
        }


        // --- 历史订单搜索 ---
        public function historyOrderS() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

                if (isset($post['lastId']) && trim($post['lastId']) != '') {
                    $lastId = trim($post['lastId'] + 0);
                } else {
                    $lastId = 0;
                }
                if($post['lastId'] == 0) {
                    $lastId = "id > ".$lastId;
                } else {
                    $lastId = "id < ".$lastId;
                }
                $orders = [];
                $orderIds = [];
                $orderPieces = [];
                if(isset($post['timeStart']) && $post['timeStart'] != '') {
                    $timeStart = strtotime("".$post['timeStart']."");

                } else {
                    $timeStart = 0;
                }
                if(isset($post['timeEnd']) && $post['timeEnd'] != '') {
                    $timeEnd = strtotime("".$post['timeEnd']."");
                } else {
                    $timeEnd = $_SERVER['REQUEST_TIME'];
                }

                $workerOrders = pieceState::getList(['worker_id' => $worker->id, ['time_add','>',$timeStart], ['time_add','<',$timeEnd]]);
                foreach ($workerOrders as $workerOrder) {
                    $orders[] =$workerOrder->piece_id;
                    $orders = array_unique($orders);
                    $orderIds[] = $workerOrder->piece_id;
                    $orderIds = array_unique($orderIds);
                }

                if(count($orderIds)>0) {
                    $sql = [];
                    if (isset($post['name']) && $post['name'] != '') {
                        $sql[] = "name_recipient like '%' " . "'" . $post['name'] . "'" . " '%' ";
                    }
                    if(isset($post['phone']) && $post['phone'] != '') {
                        $sql[] = "phone_recipient like '%' "."'".$post['phone']."'"." '%' ";
                    }
                    if(isset($post['address']) && $post['address'] != '') {
                        $sql[] = "address_recipient like '%' "."'".$post['address']."'"." '%' ";
                    }
                    $sqlS= implode(' AND ',$sql);
                    $orderIds= implode(',',$orderIds);
                    $orderPs = orderPiece::search($orderIds,$sqlS,$sql,$lastId);
                    foreach ($orderPs as $orderP) {
                        $orderPieces[] = [
                            'pieceId' => $orderP->id,
                            'pieceCode' => $orderP->piece_code,
                            'name' => $orderP->name_recipient,
                            'phone' => $orderP->phone_recipient,
                            'address' => $orderP->address_recipient,
                            'time' => date('m月d日 H:i:s', $orderP->time_add)
                        ];
                    }
                }
                $this->writeAesJson(1, [
                    'pieceCodes' => $orderPieces
                ], 1);
            }
        }

    }

}

